#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import cv2
import math
import numpy as np


def resize_ss(image, short_size=800, max_size=1333, division=32, return_scale=False):
    """
    限定短边长度的图像降采样
    Args:
        image: (np.array) 输入图像
        short_size: (int) 降采样后的短边长度，单位像素
        max_size: (int) 降采样后的长边最大长度，单位像素
        division: (int) 降采样后需要被该数字整除
        return_scale: (bool) 返回缩放比例
    Returns:
        image: (np.array) 降采样后的图像
    """
    short_size = int(short_size)
    max_size = int(max_size)
    division = int(division)

    oh, ow = image.shape[:2]
    if oh > ow:
        nh = int(float(oh) / ow * short_size)
        nw = short_size
        scale = float(short_size) / ow
        if nh > max_size:
            nh = max_size
            nw = int(float(ow) / oh * max_size)
            scale = float(max_size) / oh
    else:
        nw = int(float(ow) / oh * short_size)
        nh = short_size
        scale = float(short_size) / oh
        if nw > max_size:
            nw = max_size
            nh = int(float(oh) / ow * max_size)
            scale = float(max_size) / ow

    image = cv2.resize(image, (nw, nh))

    if nh % division != 0 or nw % division != 0:
        ch = int(math.ceil(float(nh) / division) * division)
        cw = int(math.ceil(float(nw) / division) * division)
        if len(image.shape) > 2:
            image_c = np.ones((ch, cw, image.shape[2]), dtype=image.dtype) * 114
            image_c[:nh, :nw, :] = image
        else:
            image_c = np.ones((ch, cw), dtype=image.dtype) * 114
            image_c[:nh, :nw] = image
        image = image_c

    if return_scale:
        return image, scale
    else:
        return image
